package com.an.wxpush.service.impl;

import com.an.wxpush.constant.ConfigConstant;
import com.an.wxpush.service.WaterService;
import com.an.wxpush.utils.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * @author anyingzhao
 * @create 2022-11-11 9:21
 */

@Service
public class WaterServiceImpl implements WaterService {

    @Autowired
    private ConfigConstant configConstant;
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private String  getAccessToken() {
        //这里直接写死就可以，不用改，用法可以去看api
        String grant_type = "client_credential";
        //封装请求数据
        String params = "grant_type=" + grant_type + "&secret=" + configConstant.getAppSecret() + "&appid=" + configConstant.getAppId();
        //发送GET请求
        String sendGet = HttpUtil.sendGet("https://api.weixin.qq.com/cgi-bin/token", params);
        // 解析相应内容（转换成json对象）
        JSONObject jsonObject1 = JSONObject.parseObject(sendGet);
        logger.info("微信token响应结果=" + jsonObject1);
        //拿到accesstoken
        return (String) jsonObject1.get("access_token");
    }

    @Override
    public String water() {
        String accessToken = getAccessToken();
        if (!StringUtils.hasText(accessToken)) {
            logger.error("token获取失败，请检查：公众号的，appId、appSecret");
            return "token获取失败，请检查：公众号的，appId、appSecret";
        }
        List<JSONObject> errorList = new ArrayList();
        HashMap<String, Object> resultMap = new HashMap<>();
        //遍历用户的ID，保证每个用户都收到推送
        for (String opedId : configConstant.getOpenidList()) {
            String water = "喝水";
            resultMap.put("water", water);
            logger.info("water:{}", water);
            System.out.println(errorList);
            sendMessage(accessToken, errorList, resultMap, opedId);

        }
        JSONObject result = new JSONObject();
        if (!errorList.isEmpty()) {
            System.out.println("errorList.size():"+errorList.size());
            result.put("result", "信息推送失败！");
            result.put("errorData", errorList);
            logger.info("信息推送失败！");
        } else {
            result.put("result", "信息推送成功！");
            logger.info("信息推送成功！");
        }
        return result.toJSONString();
    }

    private void sendMessage(String accessToken, List<JSONObject> errorList, HashMap<String, Object> resultMap, String opedId) {
        JSONObject templateMsg = new JSONObject(new LinkedHashMap<>());
        templateMsg.put("touser", opedId);
        //修改获取模板ID的方法  getWaterTemplateId()
        templateMsg.put("template_id", configConstant.getWaterTemplateId());
        templateMsg.put("data", new JSONObject(resultMap));
        //URL不需要改
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;

        String sendPost = HttpUtil.sendPost(url, templateMsg.toJSONString());
        JSONObject WeChatMsgResult = JSONObject.parseObject(sendPost);
        if (!"0".equals(WeChatMsgResult.getString("errcode"))) {
            JSONObject error = new JSONObject();
            error.put("openid", opedId);
            error.put("errorMessage", WeChatMsgResult.getString("errmsg"));
            errorList.add(error);
        }
    }
}
